import Vue from 'vue'
const state = {
  userinfo: {},
  userID: 21,
  orgID: 14,
  groupList: [],
  allMemberList: [],
  imgUrl: require('../assets/images/menber1.jpg')
}

const getters = {}

const mutations = {
  GET_USERINFO(state, obj) {
    state.userinfo = obj
  },
  CHANGE_ORG_ID (state, id) {
    state.orgID = id
  },
  SET_GROUPLIST(state, obj) {
    state.orgID = obj.userOrgId
    const group = []
    for (const i in obj.allOrg) {
      const item = obj.allOrg[i]
      group.push({
        value: item.id,
        label: item.name
      })
    }
    state.groupList = group
  },
  SAVE_MEMBERLIST(state, arr) {
    for (const i in arr) {
      const item = arr[i]
      item.pictureUrl = item.pictureUrl ? item.pictureUrl : state.imgUrl
    }
    state.allMemberList = arr
  }
}

const actions = {
  getUserInfo({commit, state}, obj) { // 获取和修改用户信息
    return new Promise((resolve, reject) => {
      Vue.http[obj.type](`/userinfo/${obj.id}`, obj && obj.param).then((suc) => {
        resolve(suc)
      }).catch((err) => {
        reject(err)
      })
    })
  },
  getOrgList({commit, state}, id) { // 获取组
    return new Promise((resolve, reject) => {
      Vue.http.get(`/orginfo/${id}`).then((suc) => {
        commit('SET_GROUPLIST', suc.data)
        resolve(suc)
      }).catch((err) => {
        reject(err)
      })
    })
  },
  getOrgUsers({commit, state}, id) { // 获取组内成员
    return new Promise((resolve, reject) => {
      Vue.http.get(`/orgusers/${id}`).then((suc) => {
        commit('SAVE_MEMBERLIST', suc.data)
        resolve(suc)
      }).catch((err) => {
        commit('SAVE_MEMBERLIST', [])
        reject(err)
      })
    })
  },
  getMemberList({commit, state}, username) { // 按字段模糊查找人员
    return new Promise((resolve, reject) => {
      Vue.http.get(`/usersearch/?username=${username}`).then((suc) => {
        commit('SAVE_MEMBERLIST', suc.data)
        resolve(suc)
      }).catch((err) => {
        commit('SAVE_MEMBERLIST', [])
        reject(err)
      })
    })
  }
}
export default {
  state,
  mutations,
  actions,
  getters
}
